<template>
  <div>
    <el-drawer v-model="drawer" :title="drawerTitle" :with-header="true">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="140px"
        class="demo-ruleForm"
      >
        <el-form-item label="发票名称：" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入发票名称" />
        </el-form-item>
        <el-form-item label="发票抬头：" prop="title">
          <el-input v-model="ruleForm.title" placeholder="请输入发票抬头" />
        </el-form-item>
        <el-form-item label="类别：" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择类别" filterable>
            <el-option
              v-for="item in ticketTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="金额：" prop="amount">
          <el-input-number
            v-model="ruleForm.amount"
            placeholder="请输入金额"
            style="width: 220px"
            :precision="2"
            :min="0"
          />
          &nbsp;&nbsp;元
        </el-form-item>
        <el-form-item label="文件：" v-if="ifAdd">
          <el-upload
            ref="upload"
            class="upload-demo"
            :limit="1"
            action="#"
            accept=".pdf"
            :auto-upload="false"
            v-model:file-list="fileList"
            :on-change="changUpload"
            style="width: 280px"
          >
            <template #trigger>
              <el-button type="primary" icon="Upload" :disabled="fileList.length === 1">
                上传文件
              </el-button>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="submit(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { validator } from '@/utils/numberFormat.ts'
  import {
    postCollectionTicketAdd,
    putCollectionTicketUpdate,
  } from '@/api/controller/collection-ticket-controller/index'
  import {
    postPaymentTicketAdd,
    putPaymentTicketUpdate,
  } from '@/api/controller/payment-ticket-controller/index'
  const drawer = ref(false)
  const fileList = ref([])
  //打开弹窗
  const drawerTitle = ref()
  const ifAdd = ref(true)
  const contractType = ref()
  const ticketTypeList = ref([
    { value: '普票', label: '普票' },
    { value: '专票', label: '专票' },
  ])
  const show = async (row, id, type) => {
    if (row.id) {
      ruleForm.value = { ...row }
      drawerTitle.value = '编辑发票'
      ifAdd.value = false
    } else {
      drawerTitle.value = '新增发票'
      ifAdd.value = true
      ruleForm.value = {
        contractId: id,
        name: null,
        title: null,
        type: null,
        amount: null,
      }
    }
    contractType.value = type
    fileList.value = []
    drawer.value = true
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }

  //提交的数据
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = ref({
    contractId: null,
    name: null,
    title: null,
    type: null,
    amount: null,
  })
  const rules = reactive({
    name: [
      { required: true, message: '请输入发票名称', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    type: [{ required: true, message: '请选择发票类型', trigger: 'blur' }],
    title: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
    amount: [
      { required: true, message: '请输入金额', trigger: 'blur' },
      { validator, trigger: 'blur' },
    ],
  })
  //提交
  const submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        if (fileList.value[0] || !ifAdd.value) {
          let result
          if (contractType.value === '1') {
            if (ifAdd.value) {
              const file = new FormData()
              file.append('file', fileList.value[0].raw)
              result = await postCollectionTicketAdd(ruleForm.value, file, { loading: true })
            } else {
              result = await putCollectionTicketUpdate(ruleForm.value, { loading: true })
            }
          } else {
            if (ifAdd.value) {
              const file = new FormData()
              file.append('file', fileList.value[0].raw)
              result = await postPaymentTicketAdd(ruleForm.value, file, { loading: true })
            } else {
              result = await putPaymentTicketUpdate(ruleForm.value, { loading: true })
            }
          }
          if (result.code === 200) {
            await emit('getData')
            drawer.value = false
            ElMessage.success('更新成功')
          }
        } else {
          ElMessage.warning('请上传文件')
        }
      } else {
        ElMessage.warning('请正确填写表单')
        return false
      }
    })
  }
  const changUpload = (file) => {
    const { name } = file
    //   文件类型限制
    const fileTypeFlag = /^.pdf$/.test(name.substring(name.lastIndexOf('.')).toLowerCase())
    if (!fileTypeFlag) {
      ElMessage.warning('文件类型只能是.pdf')
      fileList.value = []
      return
    }
  }
  const emit = defineEmits(['getData'])
  defineExpose({
    show,
  })
</script>
